/*---------------------------------------------------
 *  Access Package for PspyGear / Angular
 *
 *  David Connell - 10/2013
 *
 *  Account:            Model
 *  AccessCtrl:         Account Manager
 *  AccessDialogCtrl;   Login Dialog Controller
 */

'use strict'

//-----------------------------------
//       Account Service
//-----------------------------------
// User account services provide the
// singleton Account object which is
// authenitcation via a call to the
// access.Authorize action
//
var acctSvc = angular.module('AccountServices', ['WebServices']);
acctSvc.factory('Account', function(RPC){
    
    //----------------------
    // create service class
    var acct = {
        
        //-------------------------
        // Web App User Profile
        //------------------------- 
        profile: null,

        // reset to account guest user status
        init: function() { this.profile={ name: 'Guest Account', uid: '', pwd: '', role: 1 } },

        // fetch auth and profie info from server
        auth: function() {
            
            var rpcUrl = '/Ranger/go?action=access.Authorize'; 
            var params = "uid=$1&pwd=$2".$$( this.profile.uid, this.profile.pwd );

            // send request and store results
            return RPC.fire(rpcUrl, params);
        }
        
    };
    
    // initialize
    acct.init();
        
    // done
    return acct;
});

//------------------------------------
//      User Access Controller
//------------------------------------
// Manages the interaction between
// the UI and the model for logging
// in and out of the app
//
function AccessCtrl( $scope, $modal, Account) {

    // attach service to controller    
    $scope.acct = Account;
    
    //--------------------------
    // Open the modal login dialog
    $scope.openUI = function(dlgUrl){
        this.acct.profile.role = 0;
 
        // create modal and open it
        var modalInstance = $modal.open({
          templateUrl: dlgUrl,
          backdrop: 'static',
          windowClass: 'dlgMessage',
          controller: AccessDialogCtrl,
          resolve: {
    
          }
        });
        
        // process rresults 
        modalInstance.result.then(
            // authenticated succeeded
            function (profile) {
              // update with profile info from server
              $scope.acct.profile = profile;
              
              // audit trail
              $$log("[$3]: ++ User Auth: $1 ($2)".$$(profile.uid, profile.role, new Date()));
             },
             
             // authentication aborted
             function () {
              // dismissed...
              $scope.acct.init();
              $$log('++ Modal dismissed at: ' + new Date());
            });
    };
    
    //---------------------
    // Invalidate user id
    $scope.logout = function() {
        $$log("++ Logout: $1".$$($scope.acct.profile.uid));
        $scope.acct.init();
    };
    
    //--------------------------
    // Create new account
    $scope.create = function($scope) {
        
    },
    
    //--------------------------
    // Send passwd reset request    
    $scope.rqreset = function() {
        // fire mail request to user
    }
}

//-------------------------------------
//        Access Dialog Controller
//-------------------------------------
// Provide call backs for modal dialog
// and interacts with the Account
var AccessDialogCtrl = function ($scope, $modalInstance,Account) {
    // store account Service in local scope
    $scope.acct = Account;
    $scope.dlgStat = "";
    
    // go button pushed
    $scope.ok = function () {
        
        // authorize user credentials
        $scope.acct.auth().then(
        
            // successful server response 
            function (data) {
                // look for good result
                if (data.result == 200) {
                    // set logged on user                    
                    // close ui and send back
                    // validated user profile
                    $modalInstance.close(data.user);
                }
                
                // auth failure notification
                else {
                    $scope.dlgStat = "|----> $2: $1".$$(data.message, data.result);
                }
            },
            // server error notification
            function (msg, status) {
               $scope.dlgStat = "|----> Server Error ($2): $1".$$(msg,status);
            }
        );
    };
  
    // Cancel was pushed (or Esc)
    $scope.cancel = function () {
        $modalInstance.dismiss();
    };
};

acctSvc.directive('userSignOn', function() {
    return {
        // attribute directive
        restrict: 'A',
        
        // markup template
        templateUrl: '/Ranger/content/access.html',
        
        // directive instantiation action 
        link: function (scope, elem, attrs) {
            $$log("Sign on module");
    }
}});
    